package org.zjt.demo.common;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

//得到sring 的ioc容器 applicationContext。
@Component //必须加该注解
public class SpringIocContext implements ApplicationContextAware {
    private static final Logger logger = Logger.getLogger(SpringIocContext.class);
    @RemoteValue
    public Integer refreshCnt = 0;


    public static ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext arg0) throws BeansException {
        try {
            if (arg0 == null)
                throw new Exception("applicationContext is null");
        } catch (Exception e) {
            e.printStackTrace();
        }
        applicationContext = arg0;
        SpringIocContext ioc = applicationContext.getBean(SpringIocContext.class);
        List<Field> refreshFields = getRefreshFields(ioc.getClass());

        refreshFields.forEach(a -> {
                    try {
                        System.out.println(a.get(ioc));
                        a.set(ioc, 222);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
        );


        logger.error("----------applicationContext--init()------------");
    }


    public static List<Field> getRefreshFields(Class var1) {
        return Arrays.stream(var1.getDeclaredFields())
                .filter(a -> a.getAnnotation(RemoteValue.class) != null ? Boolean.TRUE : Boolean.FALSE)
                .peek( a -> {if (! a.isAccessible()) a.setAccessible(true) ;})
                .collect(Collectors.toList());
    }






}
